import {useState} from "react";
import {useSelector} from "react-redux";
import {selectAllUsers} from "../users/usersSlice";
import {useAddNewPostMutation} from "../api/apiSlice";

export const AddPostForm = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [userId, setUserId] = useState('')
  // const [addRequestStatus, setAddRequestStatus] = useState('idle')

  /**
   * Mutations hooks返回包含两个值的数组
   * 以当前代码为例，useAddNewPostMutation即是Mutations hooks
   * addNewPost是触发的函数，当addNewPost方法被执行时就会触发这个hook，然后像服务器发起请求
   * 第二个是一个对象，包含有关当前正在进行请求的元数据，包括一个isLoading表示请求状态
   */
  const [addNewPost, { isLoading }] = useAddNewPostMutation()

  // 修改标题
  const onTitleChanged = (e) => setTitle(e.target.value)
  // 修改文章内容
  const onContentChanged = (e) => setContent(e.target.value)
  // 修改用户id
  const onAuthorChanged = e => setUserId(e.target.value)

  // const dispatch = useDispatch()

  const users = useSelector(selectAllUsers)

  // const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
  // const canSave = [title, content, userId].every(Boolean) && addRequestStatus === 'idle'
  const canSave = [title, content, userId].every(Boolean) && !isLoading

  const onSavePostClicked = async () => {
    // if (title && content) {
    //   dispatch(addNewPost({title, content, userId}))
    //   setTitle('')
    //   setContent('')
    // }
    if (canSave) {
      try {
        // setAddRequestStatus('pending')
        // await dispatch(addNewPost({ title, content, user: userId })).unwrap()
        await addNewPost({ title, content, user: userId }).unwrap()
        setTitle('')
        setContent('')
        setUserId('')
      } catch (err) {
        console.error('Failed to save the post: ', err)
      }
      // finally {
      //   setAddRequestStatus('idle')
      // }
    }
  }

  const usersOptions = users.map(user => {
    return (
      <option key={user.id} value={user.id}>
        {user.name}
      </option>
    )
  })

  return (
    <section>
      <h2>添加新文章</h2>
      <form>
        <label htmlFor="postTitle">文章标题:</label>
        <input
          type="text"
          id="postTitle"
          name="postTitle"
          value={title}
          onChange={onTitleChanged}
        />
        <label htmlFor="postAuthor">Author：</label>
        <select
          id="postAuthor"
          value={userId}
          onChange={onAuthorChanged}
        >
          <option value=""></option>
          {usersOptions}
        </select>
        <label htmlFor="postContent">内容：</label>
        <textarea
          id="postContent"
          name="postContent"
          value={content}
          onChange={onContentChanged}
        />
        <button type="button" onClick={onSavePostClicked} disabled={!canSave}>保存文章</button>
      </form>
    </section>
  )
}
